import bpy
import os
dir_path = '/home/td/Code/seamresult/demo/cmake-build-debug/workstations/CX/carry-robot'
output_dir = '/home/td/Code/seamresult/demo/cmake-build-debug/workstations/CX/carry-robot2'

if not os.path.exists(output_dir):
    os.makedirs(output_dir)

bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete()

fmt=''

for file in os.listdir(dir_path):
    
    if file.endswith('.dae'):
        file_path = os.path.join(dir_path, file)
        bpy.ops.wm.collada_import(filepath=file_path)
        fmt='.dae'
           
    
    if file.endswith('.stl') or file.endswith('.STL'):
        file_path = os.path.join(dir_path, file)
        bpy.ops.wm.stl_import(filepath=file_path)
        fmt='.stl'
        

    if bpy.context.selected_objects:
        obj = bpy.context.active_object
        obj.data = obj.data.copy()
        bpy.context.view_layer.objects.active = obj 

    mod = obj.modifiers.new(name="Decimator", type='DECIMATE')
    mod.ratio = 0.4

    bpy.ops.object.modifier_apply(modifier="Decimator")
    
    mat = bpy.data.materials.new(name="GreenMaterial")
    mat.diffuse_color = (0.12, 0.698, 0.69, 1)  
    obj.data.materials.append(mat)


    output_file_name = os.path.splitext(file)[0] + fmt
    output_path = os.path.join(output_dir, output_file_name)
    
    
    if fmt==".dae":
        bpy.ops.wm.collada_export(filepath=output_path)
    elif fmt==".stl":
        bpy.ops.wm.stl_export(filepath=output_path)
        

    

    bpy.ops.object.select_all(action='DESELECT')
    bpy.ops.object.select_by_type(type='MESH')
    bpy.ops.object.delete()

print("...")
bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete()